const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken');
const R = require("@common/r");
const User = require('@models/user');

const routes = (router, pre, app) => {
  // 注册用户
  router.post(`${pre}/register`, async (req, res) => {
    const { username, password } = req.body;
    // 查看用户是否存在
    const user = await User.findOne({ where: { username } });
    if (user) return res.json(R.errMsg("该用户名已被注册"));
    // 创建用户
    await User.create({ username, password: bcrypt.hashSync(password, 10) });
    res.json(R.ok("注册成功"));
  })

  // 用户登录
  router.post(`${pre}/login`, async (req, res) => {
    const { username, password } = req.body;
    // 查看用户是否存在
    const user = await User.findOne({ where: { username } });
    if (!user) return res.json(R.errMsg("用户不存在"));
    // 比对密码
    const isValid = bcrypt.compareSync(password, user.password);
    if (!isValid) return res.json(R.errMsg("密码错误"));
    // 生成token
    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '99999999d' });
    res.json(R.ok({ accessToken: token }));
  })
};

module.exports = routes;